package com.oig.sys.msg.im.handler.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Throwables;
import com.lark.oapi.Client;
import com.lark.oapi.core.request.RequestOptions;
import com.lark.oapi.core.response.RawResponse;
import com.lark.oapi.core.token.AccessTokenType;
import com.lark.oapi.service.contact.v3.model.BatchGetIdUserReq;
import com.lark.oapi.service.contact.v3.model.BatchGetIdUserReqBody;
import com.lark.oapi.service.contact.v3.model.BatchGetIdUserResp;
import com.lark.oapi.service.contact.v3.model.UserContactInfo;
import com.oig.common.util.JsonUtil;
import com.oig.sys.msg.constants.MsgEnums;
import com.oig.sys.msg.im.domain.account.FeiShuAccount;
import com.oig.sys.msg.im.domain.req.FeiShuBatchMessageSendReq;
import com.oig.sys.msg.im.handler.BaseHandler;
import com.oig.sys.msg.vo.NoticeMsgVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企业微信群机器人 消息处理器
 */
@Slf4j
@Component
public class FeiShuHandler extends BaseHandler {

    public FeiShuHandler() {
        channelCode = MsgEnums.MsgChannel.FEI_SHU.getCode() + MsgEnums.MsgChannel.FEI_SHU.getNoticeTypeCode();
    }

    @Override
    public boolean handler(NoticeMsgVo noticeMsg) {
        try {
            FeiShuAccount account = JsonUtil.toObject(noticeMsg.getChannelConfig(), FeiShuAccount.class);
            log.debug("account:{}", account);
            Client client = Client.newBuilder(account.getAppId(), account.getAppSecret()).build();
            List<String> userIdList = getUserIdList(client, noticeMsg.getMobiles());
            log.debug("userIdList:{}", userIdList);
            if (CollectionUtil.isEmpty(userIdList)) {
                return false;
            }
            FeiShuBatchMessageSendReq body = new FeiShuBatchMessageSendReq();
            body.setMsg_type("text");
            FeiShuBatchMessageSendReq.Content content = new FeiShuBatchMessageSendReq.Content();
            content.setText(noticeMsg.getContent());
            body.setContent(content);
            body.setUser_ids(userIdList);
            RawResponse resp = client.post(
                    "https://open.feishu.cn/open-apis/message/v4/batch_send/"
                    , body
                    , AccessTokenType.Tenant);
            if (resp.getStatusCode() == 200) {
                String jsonResult = new String(resp.getBody());
                log.debug("resp body:{}", jsonResult);
                JSONObject jsonObject = JSON.parseObject(jsonResult);
                if (jsonObject.getInteger("code") == 0) {
                    return true;
                }
                log.warn("msg:{}",jsonObject.getString("msg"));
                return false;
            }
            log.error("FeiShuHandler#handler fail! result:{},params:{}", JSON.toJSONString(resp), JSON.toJSONString(noticeMsg));
        } catch (Exception e) {
            log.error("FeiShuHandler#handler fail!e:{},params:{}", Throwables.getStackTraceAsString(e), JSON.toJSONString(noticeMsg));
        }
        return false;
    }


    private List<String> getUserIdList(Client client, List<String> mobiles) throws Exception {
        if (CollectionUtil.isNotEmpty(mobiles)) {
            BatchGetIdUserReq req = BatchGetIdUserReq.newBuilder()
                    .userIdType("user_id")
                    .batchGetIdUserReqBody(BatchGetIdUserReqBody.newBuilder()
                            .mobiles(mobiles.toArray(new String[0]))
                            .build())
                    .build();
            BatchGetIdUserResp batchGetIdUserResp = client.contact().user().batchGetId(req, RequestOptions.newBuilder().build());
            if (batchGetIdUserResp.success()){
                if (batchGetIdUserResp.getData().getUserList()!=null) {
                    return Arrays.stream(batchGetIdUserResp.getData().getUserList()).map(UserContactInfo::getUserId).collect(Collectors.toList());
                }
            }
        }
        return Collections.emptyList();
    }

}

